package ge.telasi.tasks.ui.user;

import ge.telasi.tasks.LocaleManager;
import ge.telasi.tasks.TaskException;
import ge.telasi.tasks.ui.Platform;
import ge.telasi.tasks.ui.PrefUtils;
import ge.telasi.tasks.ui.ServerManager;
import ge.telasi.tasks.ui.comp.CommonDialog;
import ge.telasi.tasks.ui.log.LoggerUtils;
import java.awt.Component;
import javax.swing.JComponent;
import static ge.telasi.tasks.ui.log.LoggerUtils.manageException;
import static ge.telasi.tasks.ui.log.LoggerUtils.clearLogger;

/**
 * @author dimitri
 */
public class LoginDialog extends CommonDialog {
    private static final long serialVersionUID = -1862064072143026848L;

    public LoginDialog(Component parent) {
        super(parent, true);
        initComponents();
        getRootPane().setDefaultButton(btnLogin);

        // set last  server item
        ServerItem item = (ServerItem) PrefUtils.getObject(ServerManager.SERVER_ITEM);
        txtServer.setServerItem(item == null ? ServerItem.getDefaultServerItem() : item);

        String password = PrefUtils.getString(ServerManager.PASSWORD);
        String username = PrefUtils.getString(ServerManager.USERNAME);
        txtUsername.setText(username);
        txtPassword.setText(password);
        boolean hasUsername = username != null && username.trim().length() > 0;
        boolean hasPassword = password != null && password.trim().length() > 0;
        chkSave.setSelected(hasPassword);
        if (!hasUsername) {
            txtUsername.requestFocus();
        } else {
            txtPassword.requestFocus();
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        logger = new ge.telasi.tasks.ui.log.InlineLogger();
        btnLogin = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        titlePanel1 = new ge.telasi.tasks.ui.comp.TitlePanel();
        jLabel3 = new javax.swing.JLabel();
        txtServer = new ge.telasi.tasks.ui.user.ServerSelector();
        txtUsername = new ge.telasi.tasks.ui.comp.SuggestionText();
        txtPassword = new ge.telasi.tasks.ui.comp.SuggestionPassword();
        chkSave = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("მომხმარებლის შესვლა");

        jLabel1.setText("მომხმ. სახელი:");

        jLabel2.setText("პაროლი:");

        btnLogin.setText("შესვლა");
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });

        btnCancel.setText("გაუქმება");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        titlePanel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ge/telasi/resorces/icons48x48/gnome-fs-web.png"))); // NOI18N
        titlePanel1.setSubTitle("შეიყვანეთ მომხმარებლის სახელი და პაროლი");
        titlePanel1.setTitle("მომხმარებლის შესვლა");

        jLabel3.setText("სერვერი:");

        txtServer.setName("Server"); // NOI18N

        txtUsername.setName("User.username"); // NOI18N
        txtUsername.setSuggestion("ჩაწერეთ თქვენი მომხმარებლის სახელი");

        txtPassword.setName("User.password"); // NOI18N
        txtPassword.setSuggestion("ჩაწერეთ თქვენი პაროლი");

        chkSave.setText("დამახსოვრება");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnCancel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 289, Short.MAX_VALUE)
                .addComponent(btnLogin)
                .addContainerGap())
            .addComponent(titlePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(logger, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                    .addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                    .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                    .addComponent(chkSave, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(titlePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel3)
                    .addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chkSave)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(logger, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLogin)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        if (validateForm()) {
            String username = txtUsername.getText();
            String pswd = new String(txtPassword.getPassword());
            ServerItem si = txtServer.getServerItem();
            try {
                Platform.getDefault().login(si, username, pswd, chkSave.isSelected());
                dispose();
            } catch (Exception ex) {
                LoggerUtils.manageException(this, logger, ex);
            }
        }
    }//GEN-LAST:event_btnLoginActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnLogin;
    private javax.swing.JCheckBox chkSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private ge.telasi.tasks.ui.log.InlineLogger logger;
    private ge.telasi.tasks.ui.comp.TitlePanel titlePanel1;
    private ge.telasi.tasks.ui.comp.SuggestionPassword txtPassword;
    private ge.telasi.tasks.ui.user.ServerSelector txtServer;
    private ge.telasi.tasks.ui.comp.SuggestionText txtUsername;
    // End of variables declaration//GEN-END:variables

    boolean validateForm() {
        clearLogger(logger, allFields());
        try {
            validateServer();
            validateUsername();
            validatePassword();
            return true;
        } catch (TaskException ex) {
            manageException(this, logger, ex, allFields());
            return false;
        }
    }

    JComponent[] allFields() {
        return new JComponent[] {txtServer, txtUsername, txtPassword};
    }

    private void validateServer() {
        if (txtServer.getServerItem() == null) {
            throw new TaskException("განსაზღვრეთ სერვერი.", "Server");
        }
    }

    private void validateUsername() {
        String username = txtUsername.getText();
        if (username == null || username.trim().isEmpty()) {
            LocaleManager lm = Platform.getDefault().getLocaleManager();
            String msg = lm.getMessage("LoginDialog.enterUsername");
            throw new TaskException(msg, "User.username");
        }
    }

    private void validatePassword() {
        String pswd = new String(txtPassword.getPassword());
        if (pswd == null || pswd.trim().isEmpty()) {
            LocaleManager lm = Platform.getDefault().getLocaleManager();
            String msg = lm.getMessage("LoginDialog.enterPassword");
            throw new TaskException(msg, "User.password");
        }
    }
}
